package com.af.community.smart.business

import android.os.Bundle
import android.view.View
import android.view.inputmethod.EditorInfo
import com.af.community.smart.base.*
import com.af.community.smart.model.PeopleData
import com.af.community.smart.model.ResultData
import com.af.community.smart.utils.*
import com.af.community.smart.viewmodel.PeopleViewModel
import kotlinx.android.synthetic.main.activity_people.*
import kotlinx.android.synthetic.main.layout_empty.*
import kotlinx.android.synthetic.main.layout_list.*
import kotlinx.android.synthetic.main.layout_title_search.*
import net.idik.lib.slimadapter.SlimAdapter
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.koin.androidx.viewmodel.ext.android.getViewModel

class PeopleActivity : BaseActivity() {

    private val peopleList by lazy {
        listOf(
            ResultData("全部", ""),
            ResultData("常住人口", "1"),
            ResultData("流动人口", "2")
        )
    }
    private val list = ArrayList<PeopleData>()
    private val gridList = ArrayList<ResultData>()
    private var peopleType = ""
    private var mGridId = ""
    private var mKey = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_people)
        setToolbarVisibility(false)
        initTitle()

        mGridId = getString("gridId")
        swipe_refresh.isRefreshing = true
        getData(pageNum)

        observe("people_check") { updateList() }
    }

    override fun getViewModel() = getViewModel<PeopleViewModel>()

    override fun initTitle(title: String, name: String) {
        search_edit.hint = "请输入姓名"
        search_right.text = "添加人口"
        empty_hint.text = "暂无相关人口信息！"
        swipe_refresh.refresh { getData(1) }
        recycle_list.loadLinear(baseContext, swipe_refresh) {
            if (!isLoadingMore) {
                isLoadingMore = true
                getData(pageNum)
            }
        }

        mAdapter = SlimAdapter.create()
            .register<PeopleData>(R.layout.item_people_list) { data, injector ->
                injector.text(R.id.item_people_name, data.userName)
                    .text(
                        R.id.item_people_type,
                        when (data.baseType) {
                            "1" -> "常住人口"
                            "2" -> "流动人口"
                            else -> ""
                        }
                    )
                    .text(R.id.item_people_id, data.account?.idCardReplaceWithStar())
                    .text(R.id.item_people_unit, data.gridName)
                    .clicked(R.id.item_people) {
                        if (data.baseType.isNullOrEmpty()) return@clicked

                        startActivity<PeopleDetailActivity>(
                            "type" to data.baseType,
                            "data" to data
                        )
                    }
            }
            .attachTo(recycle_list)

        search_right.oneClick { startActivity<PeopleAddActivity>() }

        people_type.oneClick {
            getViewModel().showDropFilter(
                baseContext,
                people_type_hint,
                people_type_arr,
                people_head,
                peopleList
            ) {
                peopleType = it.type
                updateList()
            }
        }

        people_grid.oneClick {
            if (gridList.isEmpty()) {
                getViewModel().getGridList()
                    .bindLifeCycle(getLifecycleOwner())
                    .subscribeByFinally(
                        event = getViewModel(),
                        onSuccess = { items ->
                            gridList.add(ResultData("全部", ""))
                            gridList.addItems(items)
                            gridList.first { it.type == mGridId }.isChecked = true
                            if (gridList.isNotEmpty()) {
                                getViewModel().showDropFilter(
                                    baseContext,
                                    people_grid_hint,
                                    people_grid_arr,
                                    people_head,
                                    gridList
                                )
                                {
                                    mGridId = it.type
                                    updateList()
                                }
                            }
                        }
                    )
            } else {
                getViewModel().showDropFilter(
                    baseContext,
                    people_grid_hint,
                    people_grid_arr,
                    people_head,
                    gridList
                )
                {
                    mGridId = it.type
                    updateList()
                }
            }
        }

        search_close.oneClick { search_edit.setText("") }
        search_edit.addTextChangedListener(this@PeopleActivity)
        search_edit.setOnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                hideSoftInput() //隐藏软键盘

                if (search_edit.text.isBlank()) {
                    toast("请输入姓名")
                } else {
                    mKey = search_edit.trimString()
                    updateList()
                }
            }
            return@setOnEditorActionListener false
        }

    }

    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel().getPeopleList(
            "userId" to getString("userId"),
            "type" to peopleType,
            "gridId" to mGridId,
            "userName" to mKey,
            "page" to index
        )
            .bindLifeCycle(getLifecycleOwner())
            .subscribeByFinally(
                event = getViewModel(),
                onSuccess = {
                    list.apply {
                        if (index == 1) {
                            clear()
                            pageNum = index
                        }
                        addItems(it)
                        if (count(it) > 0) pageNum++
                    }

                    mAdapter.updateData(list)
                },
                onFinally = {
                    swipe_refresh.isRefreshing = false
                    isLoadingMore = false
                    empty_view.apply { if (list.isEmpty()) visible() else gone() }
                }
            )
    }

    private fun updateList() {
        swipe_refresh.isRefreshing = true

        empty_view.gone()
        if (list.isNotEmpty()) {
            list.clear()
            mAdapter.notifyDataSetChanged()
        }

        pageNum = 1
        getData(pageNum)
    }

    override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
        search_close.visibility = if (s.isEmpty()) View.GONE else View.VISIBLE
        if (s.isEmpty() && mKey.isNotEmpty()) {
            mKey = ""
            updateList()
        }
    }

}
